package logic

import (
	"context"
	"encoding/json"
	"time"
	"zhihu-new/models/cache"
	"zhihu-new/models/mysql"

	"zhihu-new/zhihurpc/internal/svc"
	"zhihu-new/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListProblemLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListProblemLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListProblemLogic {
	return &ListProblemLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListProblemLogic) ListProblem(in *zhihurpc.ListProblemRequest) (*zhihurpc.ListProblemResponse, error) {
	// todo: add your logic here and delete this line

	page := int(in.Page)
	if page <= 0 {
		page = 1
	}

	pageSize := 10
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	var problem []mysql.Problem
	query := mysql.DB.Debug().Offset(offset).Limit(pageSize).Order("created_at desc")

	get := cache.Rdb.Get(l.ctx, "problemList")
	if get.Val() == "" {
		if in.Title != "" {
			query.Where("title like ?", "%"+in.Title+"%").Find(&problem)
		}

		query.Find(&problem)

		marshal, _ := json.Marshal(problem)
		cache.Rdb.Set(l.ctx, "problemList", marshal, time.Hour*24)
	} else {

		json.Unmarshal([]byte(get.Val()), &problem)

	}

	var problemList []*zhihurpc.ListProblem

	for _, m := range problem {
		list := zhihurpc.ListProblem{
			Id:      int64(m.ID),
			Title:   m.Title,
			Context: m.Context,
			Name:    m.User.Nickname,
		}
		problemList = append(problemList, &list)
	}

	return &zhihurpc.ListProblemResponse{List: problemList}, nil
}
